package org.codehaus.janino.util.resource;

import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import org.codehaus.janino.Compiler;

/**
 * Stores a stream of bytes in a named resource.
 */
public abstract class FileResourceCreator implements ResourceCreator {

    public final OutputStream createResource(String resourceName) throws IOException {

        FileConnection file = this.getFile(resourceName);

        // Create directory for class file if it does not exist.
        //TODO create directories mkdirs
        FileConnection dir = (FileConnection) Connector.open(getParent(file.getURL()));

        if (dir != null && (!dir.exists() || !dir.isDirectory())) {
            if (!mkdirs(dir.getURL())) {
                throw new IOException("Cannot create directory for class file \"" + file + "\"");
            }
        }

        if (!file.exists()) {
            file.create();
        }

        // Create the file.
        return file.openDataOutputStream();
    }

    public final void deleteResource(String resourceName) {
        try {
            this.getFile(resourceName).delete();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static String getParent(String url) {
        int index = url.lastIndexOf('/', url.length() - 2);
        String parent = url.substring(0, index + 1);
       // System.out.println(parent);
        return parent;
    }

    public static boolean mkdirs(String url) {
        try {
           // System.out.println("mkdirs " + url);
            //E:/pasta/past1/pasta2
            FileConnection fc = (FileConnection) Connector.open(url);
            if (!fc.exists()) {
                mkdirs(getParent(url));
                fc.mkdir();
            }
        } catch (IOException ex) {
            return false;
        }
        return true;
    }

    protected abstract FileConnection getFile(String resourceName);
}
